import koa from 'koa'
import koaBody from 'koa-body'
import http from 'http'
import ip from 'ip'
import cors from 'koa2-cors'
import koaStatic from 'koa-static'
import path from 'path'
import { Server } from "socket.io"
// @ts-ignore
// import sse from "koa-sse-stream"
// @ts-ignore
import parameter from 'koa-parameter'
// import 'dotenv/config'

import mongo from './db/mongo'
import { loggerMiddleware } from './log/log'
import { errorHandler, responseHandler } from './middleware/response'
import { privateRouter, publicRouter, openRouter } from './router'

import User from "./models/gptUser"
import { createRandomString, decodeToken } from './utils/util'
import { AnyObject } from 'mongoose'
const PORT = 3333
const app = new koa()

mongo()
// 错误捕获
app.use(errorHandler)

// 日志记录
app.use(loggerMiddleware)

app.use(cors())

app.use(koaBody({ multipart: true }))

app.use(koaStatic(path.join(__dirname, '../doc')))
app.use(koaStatic(path.join(__dirname, './public')))
// app.use(sse({
//   maxClients: 5000,
//   pingInterval: 30000,
// }))

app.use(parameter(app))
app.use(publicRouter.routes()).use(publicRouter.allowedMethods()) // 公共路由
app.use(privateRouter.routes()).use(privateRouter.allowedMethods()) // 权限路由
app.use(openRouter.routes()).use(openRouter.allowedMethods()) // 公开路由

app.use(responseHandler)

const server = http.createServer(app.callback())
server.listen(PORT)

server.on('error', (err: Error) => {
  console.log(err)
})
server.on('listening', () => {
  const localhost = `http://[::1]:${PORT}`
  const ipAddress = `http://${ip.address()}:${PORT}`
  console.log(`app started at address:\n${localhost}\n${ipAddress}`)
})

const io = new Server(server, {
  cors: {
    origin: '*',
    optionsSuccessStatus: 200
  },
})

const rooms: Record<string, any> = {}
const onlineUsers: AnyObject = {}
let roomId = createRandomString(10)
io.on('connection', async (socket) => {
  const userInfo = JSON.parse(socket.handshake.query.userInfo as string)
  onlineUsers[socket.id] = userInfo
  // 监听玩家匹配
  socket.on('match', (data: any) => {
    if (!rooms[roomId]) rooms[roomId] = {}
    onlineUsers[socket.id].roomId = roomId
    rooms[roomId][socket.id] = onlineUsers[socket.id];
    socket.join(roomId)
    const matchPlayers = Object.entries(rooms[roomId]);
    console.log(rooms[roomId]);

    if (matchPlayers.length >= 2) {
      const isStart = Math.random() > 0.5
      const [user1, user2] = matchPlayers // {a:{},b:{}}
      io.to(user1[0]).emit("matchSuccess", { user: user2[1], isStart })
      io.to(user2[0]).emit("matchSuccess", { user: user1[1], isStart:!isStart })
      roomId = createRandomString(10)
    }
  })
  socket.on('stepChese', ({ x, y }) => {
    socket.to(onlineUsers[socket.id].roomId).emit('stepChese', { x, y })
  })
  socket.on('disconnect', () => {
    delete rooms[onlineUsers[socket.id].roomId]
    socket.to(onlineUsers[socket.id].roomId).emit('tip', "对手已掉线")
    delete onlineUsers[socket.id]
  })
})
